//! @Author: DengLibin 榆霖
//! @Date:  2022-04-21 13:46:51
//! @Description: 错误捕捉

//use actix_files::NamedFile;
use actix_web::{middleware::{ErrorHandlerResponse}, dev::{self}, Result, HttpResponse};

use common::pojo::ResData;




/// @Author: DengLibin 榆霖
/// @Date:  2022-04-21 15:16:00
/// @Description: 错误的请求
pub fn bad_request<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
    //返回html页面
    // let new_resp = NamedFile::open("static/errors/400.html")?
    //     .set_status_code(res.status())
    //     .into_response(res.request())
    //     .map_into_right_body();
    // Ok(ErrorHandlerResponse::Response(res.into_response(new_resp)))
    info!("错误捕捉中间件, 错误的请求格式");
    //返回json
    let r = HttpResponse::BadRequest()
        .json(ResData::fail("错误的请求格式", ""))
        .map_into_right_body();
    Ok(ErrorHandlerResponse::Response(res.into_response(r)))
    
}
/// @Author: DengLibin 榆霖
/// @Date:  2022-04-21 15:15:14
/// @Description: 资源不存在 返回404页面
pub fn not_found<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
    
    // let new_resp = NamedFile::open("static/errors/404.html")?
    //     .set_status_code(res.status())
    //     .into_response(res.request())
    //     .map_into_right_body();
    // Ok(ErrorHandlerResponse::Response(res.into_response(new_resp)))
    info!("错误捕捉中间件, 访问的资源不存在");
    //返回json
    let r = HttpResponse::NotFound()
        .json(ResData::fail("访问的资源不存在", ""))
        .map_into_right_body();
    Ok(ErrorHandlerResponse::Response(res.into_response(r)))
    

}

/// @Author: DengLibin 榆霖
/// @Date:  2022-04-21 15:15:43
/// @Description: 服务端错误
pub fn internal_server_error<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
    
    // let new_resp = NamedFile::open("static/errors/500.html")?
    //     .set_status_code(res.status())
    //     .into_response(res.request())
    //     .map_into_right_body();
    // Ok(ErrorHandlerResponse::Response(res.into_response(new_resp)))

    info!("错误捕捉中间件, 服务端内部错误");
    //返回json
    let r = HttpResponse::InternalServerError()
        .json(ResData::fail("服务端内部错误", ""))
        .map_into_right_body();
    Ok(ErrorHandlerResponse::Response(res.into_response(r)))
}